package com.mengfou;
import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;
import com.android.build.gradle.internal.api.ApplicationVariantImpl;
import com.android.build.gradle.internal.variant.BaseVariantData;
import com.mengfou.tasks.ApkVersionTask;
import com.mengfou.tasks.FirstTask;

import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;

import java.lang.reflect.Method;

/**
 * @author 梦否 on 2022/12/31
 * @blog https://mengfou.blog.csdn.net/
 */
public class HelloPlugin extends BasePlugin {

    @Override
    public void apply(Project project) {
        AppExtension appExtension = project.getExtensions().getByType(AppExtension.class);
        project.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
                for (ApplicationVariant applicationVariant : appExtension.getApplicationVariants()) {
                    try {
                        ApkVersionTask apkVersionTask = project.getTasks().create(getTaskName("reName", "Apk", applicationVariant.getName()), ApkVersionTask.class);
                        apkVersionTask.setProject(project);
                        apkVersionTask.setVariant(applicationVariant.getName());
                        //FirstTask firstTask = project.getTasks().create(getTaskName("first", "Task", applicationVariant.getName()), FirstTask.class);

                        Class<? extends ApplicationVariantImpl> aClass = ((ApplicationVariantImpl) applicationVariant).getClass();
                        Method variantData = aClass.getDeclaredMethod("getVariantData");
                        variantData.setAccessible(true);
                        BaseVariantData baseVariantData = (BaseVariantData) variantData.invoke(applicationVariant);

                        Task packageTask = project.getTasks().findByName(baseVariantData.getTaskContainer().getPackageAndroidTask().getName());
                        Task createApkListingFileRedirectTask = project.getTasks().findByName(getTaskName("create", "ApkListingFileRedirect", applicationVariant.getName()));
                        apkVersionTask.dependsOn(packageTask);
                        apkVersionTask.dependsOn(createApkListingFileRedirectTask);
                        Task assembleTask = project.getTasks().findByName(getTaskName("assemble", "", applicationVariant.getName()));
                        assembleTask.dependsOn(apkVersionTask);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
